import ldap

from config import LDAPHOST, LDAPUSER, LDAPPASSWORD


class UserCenterLDAP:
    # 设置LDAP连接参数
    ldap_host = LDAPHOST
    ldap_user = LDAPUSER
    ldap_password = LDAPPASSWORD

    @classmethod
    def ldap_connect(cls, host, username, password):
        try:
            ldap.set_option(ldap.OPT_REFERRALS, 0)
            ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

            conn = ldap.initialize(host)
            conn.simple_bind_s(username, password)
            return conn
        except ldap.LDAPError as e:
            print(e)
            return None

    @classmethod
    def ldap_search(cls, conn, base_dn, filter_str):
        try:
            result = conn.search_s(base_dn, ldap.SCOPE_SUBTREE, filter_str)
            return result
        except ldap.LDAPError as e:
            print(e)
            return None

    @classmethod
    def get_conn(cls):
        # 连接LDAP服务器
        conn = cls.ldap_connect(cls.ldap_host, cls.ldap_user, cls.ldap_password)
        return conn

    @classmethod
    def close_conn(cls, conn):
        # 关闭LDAP连接
        conn.unbind()
        return
